#include "UseThreadCount.h"
#include <thread>
#include <iostream>

UseThreadCount::UseThreadCount(const uint64_t thread_count, const uint64_t start, const uint64_t end)
	:thread_count{ thread_count }, start{ start }, end{ end }{

}

UseThreadCount::UseThreadCount(const UseThreadCount& p) {

	this->start = p.end;
	this->end = p.end;
	this->thread_count = p.thread_count;
		
}

uint64_t UseThreadCount::get_count() {
	uint64_t seg_expand = (end - start + 1) % thread_count;
	uint64_t seg_size = (end - start + 1) / thread_count;

	cout << "seg_size: " << seg_size << endl;

	vector<thread> join_list;
	vector<uint64_t> result;
	uint64_t s = start;
	uint64_t e = start + seg_size - 1;

	// init
	for (uint64_t i = 0; i < seg_size; i++) {
		result.push_back(0);
	}
	
	for (uint64_t i = 0; i < this->thread_count; i++) {
		//thread t(&UseThreadCount::add, this, ref(result[i]), s, e);
		//join_list.push_back(t);// error

		join_list.push_back(thread(&UseThreadCount::add, this, ref(result[i]), s, e));

		s = e + 1;
		e = s + seg_size - 1;
	}

	// waiting
	for (uint64_t i = 0; i < this->thread_count; i++) {
		join_list[i].join();
	}

	if (seg_expand != 0) {
		e = 0;
		while (s <= end) {
			e += s++;
		}
		result.push_back(e);
	}

	uint64_t r0 = 0;
	// add result vector
	
	for (auto c : result) {
		r0 += c;
	}

	return r0;

}

void UseThreadCount::add(uint64_t& r, uint64_t s, uint64_t e) {
	
	for (uint64_t i = s; i <= e; i++) {
		r += i;
	}

}


UseThreadCount::~UseThreadCount() {}
